import { error } from "util"

const whole = {
  id: 0,
  classify_id: 0,
  name: "全部鱼种"
}

const wholeClass = {
    id: 0,
    name: "全部鱼种"
}

export default {
  state: {
    classes: [],
    classesWithWhole: [wholeClass],
    species: {},
    speciesWithWhole: { 0: [whole] }
  },
  mutations: {
    initFishes(state, fishes) {
      state.classes = state.classes.concat(fishes.fish_classify)
      state.classesWithWhole = state.classesWithWhole.concat(fishes.fish_classify)
      // Object.assign(state.classesWithWhole, fishes.fish_classify)
      // state.classesWithWhole.unshift()

      Object.assign(state.species, fishes.fish_kind)
      const fishKind = JSON.parse(JSON.stringify(fishes.fish_kind))
      for (let k in fishKind) {
        fishKind[k].unshift(whole)
      }
      Object.assign(state.speciesWithWhole, fishKind)
    }
  },
  actions: {
    async getFishes({ commit, state, dispatch }) {
      if (state.classes.length === 0) {
        await dispatch("callFishesApi")
      }
      return state.classes
    },
    async getFishesWithWhole({ commit, state, dispatch }) {
      if (state.classesWithWhole.length === 1) {
        await dispatch("callFishesApi")
      }
      return state.classesWithWhole
    },
    async callFishesApi({ commit, state }) {
      const ret = await axios.get("/api/common/getFish")
      let data = ret.data
      if (data.resp_msg.msg_code === 200) {
        commit("initFishes", ret.data.resp_data)
        return
      } else {
        throw new error("Can not get fishes.")
      }
    },
    async getSpecise({ state, dispatch }, cid) {
      if (getObjectLength(state.speciesWithWhole) === 0) {
        await dispatch("callFishesApi")
      }
      for (let k in state.species) {
        if (Number(k) === cid) {
          return state.species[k]
        }
      }
      throw new Error("No species.")
    },
    async getSpeciseWithWhole({ state, dispatch }, cid) {
      if (getObjectLength(state.speciesWithWhole) === 1) {
        await dispatch("callFishesApi")
      }
      for (let k in state.speciesWithWhole) {
        if (Number(k) === cid) {
          return state.speciesWithWhole[k]
        }
      }
      throw new Error("No species.")
    }
  }
}

function getObjectLength(obj) {
  //排除__obj__
  return Object.getOwnPropertyNames(obj).length - 1
}
